package com.test.springboot.springBootUtils.service.shell;

import com.test.springboot.springBootUtils.bean.Person;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.util.annotation.Nullable;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class PersonConverter implements Converter<String, Person> {
    private final Pattern pattern=Pattern.compile("\\(#(\\d+)\\).*");
    private final CrmService crm;

    public PersonConverter(CrmService crm) {
        this.crm = crm;
    }

    @Nullable
    @Override
    public Person convert(String source) {
        Matcher matcher = this.pattern.matcher(source);

        if(matcher.find()){
            String group = matcher.group(1);

            if(StringUtils.hasText(group)){
                long id = Long.parseLong(group);
              return   this.crm.findById(id);
            }
        }
        return null;
    }
}
